package com.example.sea.core.data.user.service;

import com.alibaba.druid.util.StringUtils;
import com.example.sea.core.common.utils.UUIDUtil;
import com.example.sea.core.data.user.AuthPermissionEnum;
import com.example.sea.core.data.user.entity.AuthPermission;
import com.example.sea.core.data.user.mapper.AuthPermissionMapper;
import com.example.sea.core.data.user.mapper.AuthRoleMapper;
import com.example.sea.core.data.user.model.AuthPermissionModel;
import com.example.sea.core.data.user.model.AuthRolePermissionModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 描述：
 *
 * @author zengyz
 * @date 2018/7/9 上午 11:54
 */
@Service
public class AuthPermissionService {

    @Autowired
    private AuthPermissionMapper authPermissionMapper;

    @Autowired
    private AuthRoleMapper authRoleMapper;

    /**
     * 查询菜单树
     * @param treeType
     * @return
     */
    public List<AuthPermissionModel> findTree(Integer treeType) {
        List<AuthPermissionModel> treeList = new ArrayList<>();
        List<AuthPermission> authPermissionsLevel_1 = authPermissionMapper.selectListByParamsMap(setAuthParamsByTree(treeType, String.valueOf(AuthPermissionEnum.PERMISSION_PARENT_ID.getValue()), AuthPermissionEnum.STATE_OK.getValue()));
        for (AuthPermission authPermission1 : authPermissionsLevel_1) {
            AuthPermissionModel authPermissionModel = setAuthPermissionModel(authPermission1);
            List<AuthPermission> authPermissionsLevel_2 = authPermissionMapper.selectListByParamsMap(setAuthParamsByTree(treeType, authPermission1.getId(), AuthPermissionEnum.STATE_OK.getValue()));
            for (AuthPermission authPermission2 : authPermissionsLevel_2) {
                AuthPermissionModel authPermissionModelTemp = setAuthPermissionModel(authPermission2);
                //一级菜单里面添加二级菜单
                authPermissionModel.getAuthPermissionModels().add(authPermissionModelTemp);
            }
            //添加一级菜单
            treeList.add(authPermissionModel);
        }
        return treeList;
    }


    /**
     * 查询菜单
     * @param params
     * @return
     */
    public PageInfo<AuthPermission> findPageByParams(Map params){
        PageHelper.startPage(Integer.valueOf(params.get("pageNum").toString()),Integer.valueOf(params.get("pageSize").toString()));
        List<AuthPermission> authPermissions = authPermissionMapper.selectListByParamsMap(params);
        PageInfo<AuthPermission> pageInfo = new PageInfo<>(authPermissions);
        return pageInfo;
    }

    /**
     * 添加
     * @param authPermission
     * @return
     */
    @Transactional
    public int add(AuthPermission authPermission){
        authPermission.setId(UUIDUtil.getUUID32());
        authPermission.setCreateTime(new Date());
        authPermission.setParentId(StringUtils.isEmpty(authPermission.getParentId())?String.valueOf(AuthPermissionEnum.PERMISSION_PARENT_ID.getValue()):authPermission.getParentId());
        authPermission.setType(AuthPermissionEnum.TYPE_BACK_PERMISSION.getValue());
        authPermission.setPath(StringUtils.isEmpty(authPermission.getPath())?"javascript:void(0)":authPermission.getPath());

        //给管理员角色添加权限
        Map params=new HashMap();
        params.put("roleId","9e7c4d587fea4b55bec1ab952e341439");
        params.put("permissionId",authPermission.getId());
        authRoleMapper.insertRolePermission(params);

        return authPermissionMapper.insert(authPermission);
    }

    /**
     * 修改
     * @param authPermission
     * @return
     */
    @Transactional
    public int update(AuthPermission authPermission){
        return authPermissionMapper.updateByPrimaryKey(authPermission);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Transactional
    public int delete(String[] ids){
        int count=0;
        for (String id:ids) {
            //先查询是否有角色关联权限，如果有则不能删除
            List<AuthRolePermissionModel> authRolePermissionModels = authRoleMapper.selectListByPermissionIdToRolePermission(id);
            if (CollectionUtils.isEmpty(authRolePermissionModels)){
                AuthPermission authPermission = authPermissionMapper.selectByPrimaryKey(id);
                if (authPermission.getParentId().equals(String.valueOf(AuthPermissionEnum.PERMISSION_PARENT_ID.getValue()))){
                    Map params=new HashMap();
                    params.put("parentId",id);
                    List<AuthPermission> authPermissions = authPermissionMapper.selectListByParamsMap(params);
                    for (AuthPermission authPermissionTemp:authPermissions) {
                        authPermissionMapper.deleteByPrimaryKey(authPermissionTemp.getId());
                    }
                    count += authPermissionMapper.deleteByPrimaryKey(id);
                }else{
                    count += authPermissionMapper.deleteByPrimaryKey(id);
                }
            }
        }
        return count;
    }

    /**
     * 根据ID进行查询
     * @param id
     * @return
     */
    public AuthPermission findById(String id){
        return authPermissionMapper.selectByPrimaryKey(id);
    }

    /**
     * 设置查询参数
     * @param type
     * @param parentId
     * @param state
     * @return
     */
    private Map setAuthParamsByTree(Integer type, String parentId, Integer state) {
        Map paramsTree1 = new HashMap();
        paramsTree1.put("type", type);
        paramsTree1.put("parentId", parentId);
        paramsTree1.put("state", state);
        return paramsTree1;
    }

    /**
     * 实体转model
     * @param authPermission
     * @return
     */
    private AuthPermissionModel setAuthPermissionModel(AuthPermission authPermission) {
        AuthPermissionModel authPermissionModel = new AuthPermissionModel();
        authPermissionModel.setId(authPermission.getId());
        authPermissionModel.setType(authPermission.getType());
        authPermissionModel.setCode(authPermission.getCode());
        authPermissionModel.setName(authPermission.getName());
        authPermissionModel.setPath(authPermission.getPath());
        authPermissionModel.setIcon(authPermission.getIcon());
        authPermissionModel.setSort(authPermission.getSort());
        authPermissionModel.setState(authPermission.getState());
        authPermissionModel.setCreateTime(authPermission.getCreateTime());
        authPermissionModel.setAuthPermissionModels(new ArrayList<AuthPermissionModel>());
        return authPermissionModel;
    }

}
